<#
.SYNOPSIS
  Generates translations.dart directly
.DESCRIPTION
  Simplified structure without generated subfolder
#>

# 1. 设置UTF-8编码
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8

# 2. 定位项目根目录
$rootDir = $PWD.Path
while ($rootDir -ne "" -and -not (Test-Path (Join-Path $rootDir "pubspec.yaml"))) {
  $rootDir = Split-Path $rootDir -Parent
}

if (-not $rootDir) {
  Write-Host "ERROR: Not in Flutter project" -ForegroundColor Red
  exit 1
}

# 3. 设置路径
$SOURCE_DIR = Join-Path $rootDir "lib/generated/translations/sources"
$OUTPUT_FILE = Join-Path $rootDir "lib/generated/translations/translations.dart"

# 4. 处理JSON文件
$translations = @{}

Get-ChildItem -Path $SOURCE_DIR -Filter "*.json" | ForEach-Object {
  try {
    $langCode = $_.BaseName
    $jsonContent = [System.IO.File]::ReadAllText($_.FullName, [System.Text.Encoding]::UTF8)

    if ([string]::IsNullOrWhiteSpace($jsonContent)) {
      Write-Host "WARNING: Empty file $($_.Name)" -ForegroundColor Yellow
      return
    }

    $jsonObj = $jsonContent | ConvertFrom-Json
    $nestedTranslations = @{}

    # 递归处理嵌套结构
    function Process-Node {
      param($node, $prefix)

      $node.PSObject.Properties | ForEach-Object {
        $fullKey = if ($prefix) { "${prefix}.$($_.Name)" } else { $_.Name }

        if ($_.Value -is [PSCustomObject]) {
          Process-Node -node $_.Value -prefix $fullKey
        } else {
          $nestedTranslations[$fullKey] = $_.Value.ToString()
        }
      }
    }

    Process-Node -node $jsonObj -prefix ""
    $translations[$langCode] = $nestedTranslations

    Write-Host "Processed: $($_.Name) ($($nestedTranslations.Count) keys)" -ForegroundColor Gray
  } catch {
    Write-Host "ERROR processing $($_.Name): $_" -ForegroundColor Red
  }
}

# 5. 生成完整的translations.dart文件
$dartCode = @"
// GENERATED CODE - DO NOT MODIFY BY HAND
// Generated at: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')

import 'package:get/get.dart';

class AppTranslations extends Translations {
  @override
  Map<String, Map<String, String>> get keys => {
$(
($translations.GetEnumerator() | Sort-Object Name | ForEach-Object {
  $lang = $_.Key
  $map = $_.Value

  "    '$lang': {"
  ($map.GetEnumerator() | Sort-Object Name | ForEach-Object {
    $value = $_.Value -replace "'", "''" -replace "\n", " "
    "      '$($_.Key)': '$value',"
  }) -join "`n"
  "    },"
}) -join "`n"
)
  };
}

// 使用示例：
// GetMaterialApp(
//   translations: AppTranslations(),
//   locale: Locale('zh', 'CN'),
//   fallbackLocale: Locale('en', 'US'),
// )
"@

# 6. 写入文件
try {
  [System.IO.File]::WriteAllText($OUTPUT_FILE, $dartCode, [System.Text.Encoding]::UTF8)
  Write-Host "SUCCESS: Generated translations.dart" -ForegroundColor Green
  Write-Host "Location: $OUTPUT_FILE" -ForegroundColor Cyan
} catch {
  Write-Host "ERROR writing file: $_" -ForegroundColor Red
  exit 1
}

exit 0